package com.home.qh.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.Vessel;
import com.home.qh.model.Voyage;
import com.home.qh.service.VesselManager;
import com.home.qh.service.VoyageManager;

@Controller
public class VoyageController{
	private transient final Log log = LogFactory.getLog(VoyageController.class);
	private VesselManager vesselManager;
	private VoyageManager voyageManager;
	
	@Autowired
	private ApplicationContext context;
	
	@Autowired
	public void setVesselManager(VesselManager vesselManager){
		this.vesselManager = vesselManager;
	}
	
	@Autowired
	public void setVoyageManager(VoyageManager voyageManager){
		this.voyageManager = voyageManager;
	}
	
	@RequestMapping(value = "/admin/voyage_list.*", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView listVoyages(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("entering 'handleRequest' method...");
		}
		
		Voyage voyageSearch = new Voyage();
		String paramValue = request.getParameter("name");
		String paramVesselValue = request.getParameter("vessel");
		
		if (paramValue != null && !"".equalsIgnoreCase(paramValue.trim())
				&& !"null".equalsIgnoreCase(paramValue)) {
			voyageSearch.setName(paramValue);
			voyageSearch.setCode(paramValue);
		}
		
		if (paramVesselValue != null
				&& !"".equalsIgnoreCase(paramVesselValue.trim())
				&& !"null".equalsIgnoreCase(paramVesselValue)) {
			Long paramVesselId = null;
			try {
				paramVesselId = Long.parseLong(paramVesselValue);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (paramVesselId != null) {
				Vessel vesselSearch = new Vessel();
				vesselSearch.setId(paramVesselId);
				voyageSearch.setVessel(vesselSearch);
			}else{
				voyageSearch.setVessel(null);
			}
		}
		
		ModelAndView view = new ModelAndView("admin/voyage_list");
		view.addObject("listVessels", vesselManager.getAll());
		view.addObject("voyageSearch", voyageSearch);
		
		view.addObject("listVoyages", voyageManager.getVoyageByVoyage(voyageSearch, null, false, -1, -1));
		
		return view;
	}
}